package com.yonghui.springsecurityoauth2demo.controller;

import cn.hutool.json.JSONUtil;
import com.yonghui.springsecurityoauth2demo.config.CaffeineJwtTokenStore;
import com.yonghui.springsecurityoauth2demo.domain.OauthUser;
import com.yonghui.springsecurityoauth2demo.pojo.ResultCode;
import com.yonghui.springsecurityoauth2demo.pojo.ResultVo;
import com.yonghui.springsecurityoauth2demo.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @author liyonghui
 * @description: TODO
 * @date 2021/12/5 13:50
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private CaffeineJwtTokenStore jwtTokenStore;

    @Autowired
    private CheckTokenEndpoint checkTokenEndpoint;

    @Autowired
    private ConsumerTokenServices tokenServices;
    /**
     * @description: 获取当前用户
     * @author liyonghui
     * @date 2021/12/5 13:52
     */
    @RequestMapping("getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        return authentication.getPrincipal();
    }

    /**
     * @description: 解析JWT
     * @author liyonghui
     * @date 2021/12/5 16:18
     */
    @RequestMapping("getCurrentUser1")
    public Object getCurrentUser1(Authentication authentication, HttpServletRequest request) {
        String head = request.getHeader("Authorization");
        String token = head.substring(head.indexOf("bearer") + 7);
        Claims body = Jwts.parser().setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token).getBody();
        return body;
    }

    /**
     * @description: 使用SecurityUtils获取当前用户信息
     */
    @RequestMapping("getCurrentUser2")
    public Object getCurrentUser1() {
        // 直接从 SecurityUtils 获取用户详情
        OauthUser user = SecurityUtils.getLoginUser().getUser();
        System.out.println(JSONUtil.toJsonStr(user));
        return user;
    }

    @RequestMapping("getUserInfo")
    public ResultVo getUserInfo() {
        // 直接从 SecurityUtils 获取用户详情
        OauthUser user = SecurityUtils.getLoginUser().getUser();
        System.out.println(JSONUtil.toJsonStr(user));
        ResultVo vo = new ResultVo();
        vo.setCode(200);
        vo.setMsg("success");
        vo.setData(user);
        return vo;
    }

    /**
     * 检查token
     * @param token
     * @return
     */
    @PostMapping("/check_token")
    public ResultVo<OAuth2AccessToken> checkToken(HttpServletRequest request) {
        String head = request.getHeader("Authorization");
        String token = head.substring(head.indexOf("bearer") + 7);
        OAuth2AccessToken accessToken = jwtTokenStore.readAccessToken(token);
        if (accessToken == null) {
            return ResultVo.resultFail(ResultCode.TOKEN_ERROR);
        }
        if (accessToken.isExpired()) {
            return ResultVo.resultFail(ResultCode.TOKEN_ERROR);
        }
        // 如果需要，可以返回其他关于 token 的信息
        return ResultVo.resultSuccess(accessToken);
    }

    /**
     * 回收token
     * @param token
     * @return
     */
   @PostMapping("/revoke_token")
   public ResultVo<OAuth2AccessToken> revokeToken(HttpServletRequest request) {
       String head = request.getHeader("Authorization");
       String token = head.substring(head.indexOf("bearer") + 7);
       OAuth2AccessToken accessToken = jwtTokenStore.readAccessToken(token);
       if (accessToken == null) {
           return ResultVo.resultFail(ResultCode.TOKEN_ERROR);
       }
       jwtTokenStore.removeAccessToken(accessToken);
       return ResultVo.resultSuccess("success");
   }

    @PostMapping("/refresh_token")
    public ResultVo<OAuth2AccessToken> refreshToken(HttpServletRequest request) {
        String head = request.getHeader("Authorization");
        String token = head.substring(head.indexOf("bearer") + 7);
        OAuth2AccessToken accessToken = jwtTokenStore.readAccessToken(token);
        if (accessToken == null) {
            return ResultVo.resultFail(ResultCode.TOKEN_ERROR);
        }
        OAuth2Authentication oAuth2Authentication = jwtTokenStore.readAuthentication(token);
        if (oAuth2Authentication == null) {
            return ResultVo.resultFail(ResultCode.TOKEN_ERROR);
        }
        jwtTokenStore.refreshAccessToken(accessToken,oAuth2Authentication);

        return ResultVo.resultSuccess(accessToken);
    }


}
